package mc.contents.web.servlet;

import mc.contents.dao.ShopInfoMapper;
import mc.contents.pojo.persistence.ShopInfo;
import mc.contents.etc.CrawHandler;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
/**
 * Created by LuoHui on 14-11-26.
 */
@WebServlet(name = "dsrRequest",urlPatterns="/crawDsr",asyncSupported=true)
public class DsrRequestServlet extends HttpServlet {
    private static Logger log = LoggerFactory.getLogger( DsrRequestServlet.class );
    private ShopInfoMapper shopInfoMapper;
    private CrawHandler crawHandler;

    @Override
    public void init( ServletConfig config ) throws ServletException {
        super.init( config );
        ServletContext servletContext = config.getServletContext();
        WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext( servletContext );
        shopInfoMapper = (ShopInfoMapper) context.getBean( "shopInfoMapper" );
        crawHandler = (CrawHandler) context.getBean( "crawHandler" );
    }

    @Override
    protected void doPost( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException {
        doGet( req,resp );
    }

    protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
        String nick = request.getParameter( "nick" );
        if( StringUtils.isNotEmpty( nick )){
            final ShopInfo shopInfo = shopInfoMapper.getShopInfoByNick( nick );

            //url is null
            if(shopInfo==null){
                crawHandler.crawShopUrl( nick );
            }else{
                //dsr
                if(shopInfo.getShopUrl()!=null){
                    if( shopInfo.getDt()==null || shopInfo.getDt().getDate()!=new Date(  ).getDate() ){
                        crawHandler.crawDsr(shopInfo);
                        crawHandler.crawShop4C( shopInfo );
                    }
                }else{
                    log.error("{} shop not null,but url is null",nick);
                }
            }
        }
    }
}
